package pCloud.service;

import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

import pCloud.client.DataUserCryptoHandle;
import pCloud.crypto.kpabe.TransformedCipherMessage;
import pCloud.crypto.kpabe.UKMessage;
import pCloud.message.Message;
import pCloud.message.NumberMessage;
import pCloud.message.cloud.DataMessage;

/**
 * Handle messages sent from the proxy back to the client
 * 
 */
public class DataUserClientProtocol extends ProtocolHandle {

	int counter = 0;
	boolean printingData = true;
	long startTime; 
	String timeLogFile=null; 
	int nReplies = 1; //number of replies expected. This depends on the number of requested resources and 
			
	DataUserCryptoHandle duch;

	public DataUserClientProtocol(){
		duch = new DataUserCryptoHandle();
	}
	
	@Override
	public void receive(Object o) throws Exception {
		Message msg = (Message)o;
		if (msg instanceof UKMessage){
			duch.initialize((UKMessage)msg);
		}
		else if (msg instanceof TransformedCipherMessage){
			duch.decrypt((TransformedCipherMessage)msg);
		}		

	}

	@Override
	public void send(Object m) throws Exception {
		conn.send(m);
	}
	
	
	public void setNumberOfReplies(int nReplies){
		this.nReplies = nReplies;
		System.out.println("Number of replies = "+nReplies);
	}
	
	public void setPrintingDataOption(boolean b){
		this.printingData = b;
	}
	
	public void setTimeLogFile(String fileName){
		this.timeLogFile = fileName;
	}
	
	public void initStartTime(){
		this.startTime = System.currentTimeMillis();
	}
	
	private void outputTime(String messageClassName) throws IOException{
		long endTime = System.currentTimeMillis();
		double time = (endTime - startTime)*1.0/1000;
		if (this.timeLogFile!=null){
			PrintWriter writer = new PrintWriter(new FileWriter(this.timeLogFile,true));			
			writer.println(messageClassName+" "+this.startTime+" - "+endTime+" - "+time);
			writer.close();
		}
		else
			System.out.println("Time: "+this.startTime+" - "+endTime+ " - "+time);
		
	}
}
